package com.qianfeng.smartmetting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianfeng.smartmetting.config.DBUserDetailsManager;
import com.qianfeng.smartmetting.entity.User;
import com.qianfeng.smartmetting.mapper.UserMapper;
import com.qianfeng.smartmetting.service.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
public class UserDaoImpl extends ServiceImpl<UserMapper, User> implements UserDao {

    @Autowired
    private DBUserDetailsManager dbUserDetailsManager;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Integer saveUserDetails(User user) {
        //判断用户名是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user.getUserName());
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1!=null){
            return 2;
        }

        //生成Security中的用户对象，主要是密码加密
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withDefaultPasswordEncoder()
                .username(user.getUserName())
                .password(user.getUserPassword())
                .roles(user.getUserRole())
                .build();
        dbUserDetailsManager.createUser(userDetails);

        //将生成的加密密码 存入数据库
        user.setUserPassword(userDetails.getPassword());
        int flag = userMapper.insert(user);
        return flag;
    }
}
